package com.example.parsing;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.parsing.listener.TxtListener;
import com.example.parsing.producer.TxtProducer;
import com.example.parsing.unit.Esn;
import com.example.parsing.unit.NoGenerator;
import com.example.parsing.unit.StringReplace;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Component
public class TxtMessageHandler implements MessageHandler {
	
	
	private static final Logger logger = LoggerFactory.getLogger(TxtMessageHandler.class);
	
	private static final List<String> numList = new ArrayList<>(); //保存已经注册过的设备
	
	private static final List<String> fileList = new ArrayList<>(); //保存执行过的文件
	
	private List<String> date1 = new ArrayList<>();  //从json文本读到的数据
	
	private List<String> date2 = new ArrayList<>();   //从json文本读到的数据
	
	private List<String> date3 = new ArrayList<>();   //从json文本读到的数据
	
	private List<String> date4 = new ArrayList<>();   //从json文本读到的数据
	
	@Value("${myAddress.DEVICETYPE2}")
	private String deviceType;
	
	private final KafkaTemplate<String, String> kafkaTemplate;
	
	public TxtMessageHandler(KafkaTemplate<String, String> kafkaTemplate) {
		this.kafkaTemplate = kafkaTemplate;
	}
	
	//处理txt文件夹里面的json文本
	@Override
	public void handleMessage(Message<?> message) throws MessagingException {
		logger.info("txtHandler准备处理消息---");
		File source = (File)message.getPayload();
		String path = source.getPath();
		try{
			BufferedReader br = new BufferedReader(new FileReader(path));
			MessageHeaders mhs = message.getHeaders();
			String sourceName = (String) mhs.get("file_name");
			JSONObject jsonObject = (JSONObject) JSON.parse(br.readLine());
			date1 = (List<String>) jsonObject.get("第一行数据");
			date2 = (List<String>) jsonObject.get("第二行数据");
			date3 = (List<String>) jsonObject.get("第三行数据");
			date4 = (List<String>) jsonObject.get("第四行数据");
			String deviceName = date1.get(0);
			if (!fileList.contains(sourceName)){
				if (!numList.contains(deviceName)){
					// 说明为注册，进行注册
					numList.add(deviceName);
					register(deviceName,sourceName);
				}else {
					// 说明已经注册过，进行上报数据
					dateReport(deviceName,sourceName);
				}
			}
			
		}catch (Exception e){
			logger.error("解析txt文本的json出错,出错类型是="+e);
		}
	}
	
	
	public void register(String deviceName,String sourceName){
		deviceName = StringReplace.replace2(deviceName);
		String esn = Esn.createID(); //生成esn
		new TxtProducer().register(esn,deviceName,deviceType,kafkaTemplate);
		dateReport(deviceName,sourceName);
	}
	
	public void dateReport(String deviceName,String sourceName){
		long date = new Date().getTime();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		JSONArray jsonArray = new JSONArray();
		for (int i =0;i<date2.size();i++){
			JSONObject json = new JSONObject();
			json.put("speed",date2.get(i));
			json.put("BrakingTorque",date3.get(i));
			json.put("FrictionCoefficient",date4.get(i));
			json.put("ExperimentInfoTime",sdf.format(date+(1000*i)));
			jsonArray.add(json);
		}
		JSONObject reportJson = new JSONObject();
		JSONObject requestJson = new JSONObject();
		reportJson.put("id", NoGenerator.getUUID());
		reportJson.put("requestTime",String.valueOf(NoGenerator.getDate()));
		deviceName = StringReplace.replace2(deviceName);
		String deviceId = TxtListener.deviceName.get(deviceName);
		reportJson.put("deviceId",deviceId);
		reportJson.put("modelName",deviceType);
		requestJson.put("serviceProperties",jsonArray);
		reportJson.put("request",requestJson);
		logger.info("上报的第一次数据是="+reportJson.toJSONString());
		kafkaTemplate.send("sys." + deviceType + ".thing.serviceid.property.post", deviceType, reportJson.toJSONString());
		report2(deviceName,sourceName);
	}
	
	public void report2(String deviceName,String sourceName){
		JSONArray jsonArray = new JSONArray();
		JSONObject jsonObject = new JSONObject();
		List<String> txtConfigList = ConfigProperties.readTxtConfig();
		for (int i =0;i<txtConfigList.size();i++){
			jsonObject.put(txtConfigList.get(i),date1.get(i));
		}
		jsonArray.add(jsonObject);
		JSONObject reportJson = new JSONObject();
		JSONObject requestJson = new JSONObject();
		reportJson.put("id", NoGenerator.getUUID());
		reportJson.put("requestTime", String.valueOf(NoGenerator.getDate()));
		String deviceId = TxtListener.deviceName.get(deviceName);
		reportJson.put("deviceId",deviceId);
		reportJson.put("modelName",deviceType);
		requestJson.put("serviceProperties",jsonArray);
		reportJson.put("request",requestJson);
		kafkaTemplate.send("sys." + deviceType + ".thing.serviceid.property.post", deviceType, reportJson.toJSONString());
		logger.info("第二次数据上传，上传的数据是="+reportJson.toJSONString());
		if (deviceId != null){
			fileList.add(sourceName);
		}
	}
}
